__DEBUG__= False
import os
import sys

###################################  pairwise interface  #######################################
def warp(target_brain, object_brain, data_location, result_location):
    target_image=data_location+"/"+target_brain+".hdr" 
    object_image=data_location+"/"+object_brain+".hdr" 
    #os.chdir(result_location)
    import subprocess
    subprocess.check_call([binary_path+"/IHWarpMouse", target_image, object_image])

def linear_registration(target_brain, object_brain, data_location, result_location):
    target_image=data_location+"/"+target_brain+".hdr" 
    object_image=data_location+"/"+object_brain+".hdr" 
    #os.chdir(result_location)
    import subprocess
    subprocess.call([binary_path+"/LinCoregL3", target_image, object_image, "CC", "-dir", os.path.abspath(os.path.curdir), "-o", object_brain])
    #subprocess.call([binary_path+"/LinCoregL3", target_image, object_image, "CC", "-o", object_brain])

def linear_registration_then_warp(target_brain, object_brain, data_location, result_location):
    target_image=data_location+"/"+target_brain+".hdr" 
    object_image=data_location+"/"+object_brain+".hdr" 
    #os.chdir(result_location)

    import subprocess
    if not os.path.exists(result_location+"/"+object_brain+".hdr"):
        subprocess.call([binary_path+"/LinCoregL3", target_image, object_image, "CC", "-dir", os.path.abspath(os.path.curdir), "-o", object_brain])
        #subprocess.call([binary_path+"/LinCoregL3", target_image, object_image, "CC", "-o", object_brain])

    #object_image=result_location+"/"+object_brain+".hdr" 
    object_image=os.path.abspath(os.path.curdir)+"/"+object_brain+".hdr" 
    if not os.path.exists("warp"):
        os.mkdir("warp")
    os.chdir("warp")
    subprocess.check_call([binary_path+"/IHWarpMouse", target_image, object_image])
    import shutil
    shutil.copy("final_params", "../")
    
    
if __name__=="__main__" :
    import ConfigParser
    config=ConfigParser.SafeConfigParser(defaults=dict({"working_directory":'.'}))
    config_file = os.path.abspath(os.path.expanduser(sys.argv[1]))
    if os.path.exists(config_file):
        config.read(config_file)
    else:
        print >> sys.stderr, 'config_file does not exist'
        sys.exit(1)

    binary_path = os.path.abspath(os.path.expanduser(config.get('pairwise','binary_path')))

    if not __DEBUG__:
        action=sys.argv[2]
        brain1=sys.argv[3]
        brain2=sys.argv[4]
        domain=sys.argv[5]
        codomain=sys.argv[6]
        globals()[action](brain1,brain2,domain,codomain)
    else:
        import logging
        logger = logging.getLogger("actions")
        logger.setLevel(10)
        formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
        ch = logging.StreamHandler()
        ch.setLevel(10)
        ch.setFormatter(formatter)
        logger.addHandler(ch)
